import CryptoJS from 'crypto-js';
import top from './MD5';

const ryutil = {
  //RSA 位数，这里要跟后端对应
  bits: 1024,
  //当前JSEncrypted对象
  thisKeyPair: {},
  //生成密钥对(公钥和私钥)
  genKeyPair: function (bits = ryutil.bits) {
    let genKeyPair = {};
    ryutil.thisKeyPair = new JSEncrypt({default_key_size: bits});
    //获取私钥
    genKeyPair.privateKey = ryutil.thisKeyPair.getPrivateKey();
    //获取公钥
    genKeyPair.publicKey = ryutil.thisKeyPair.getPublicKey();
    return genKeyPair;
  },
  /**
   * 加密
   *
   * @param word
   * @returns {*}
   */
  encryptaes: function (plaintext, key) {
    if (plaintext instanceof Object) {
      //JSON.stringify
      plaintext = JSON.stringify(plaintext);
    }
    let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(plaintext), CryptoJS.enc.Utf8.parse(key), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    return encrypted.toString();
  },
  /**
   * 使用MD5加密
   *
   */
  encrypt: function (needPass) {
    return top.hex_md5(needPass);
  },
  /**
   * 解密
   *
   * @param word
   * @returns {*}
   */
  decryptaes: function (ciphertext, key) {
    let decrypt = CryptoJS.AES.decrypt(ciphertext, CryptoJS.enc.Utf8.parse(key), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    let decString = CryptoJS.enc.Utf8.stringify(decrypt).toString();
    if (decString.charAt(0) === '{' || decString.charAt(0) === '[') {
      //JSON.parse
      decString = JSON.parse(decString);
    }
    return decString;
  },
};

export default ryutil;
